package com.jsmtr.rms.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jsmtr.rms.entity.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jsmtr.rms.service.IRecommendService;
import com.jsmtr.rms.service.IDoZZService;
import com.jsmtr.rms.service.ISchoolService;
import com.jsmtr.rms.service.IUtilService;
import com.jsmtr.rms.utils.EnumTools;


@Controller
@RequestMapping("/Do/ZZPost")
public class DoZZPostController {

    @Resource
    private IUtilService utilService;

    @Resource
    private IRecommendService recommendService;

    @Resource
    private ISchoolService schoolService;

    @Resource
    private IDoZZService doZZService;


    //[start] 查询毕业生信息

    //首页
    @RequestMapping("/")
    public String Index(HttpServletRequest request, Model model) {
        try {
            model.addAttribute("path", request.getContextPath());
            String pid = request.getParameter("pid").trim();
            String fid = request.getParameter("fid").trim();
            String deptcode = request.getParameter("deptcode").trim();

            model.addAttribute("pid", pid);
            model.addAttribute("fid", fid);
            model.addAttribute("deptcode", deptcode);

            StringBuilder str = new StringBuilder();
            List<HRSchoolUsers> schools = schoolService.getSchools();
            for (HRSchoolUsers school : schools) {
                str.append("<option value='" + school.getId() + "'>" + school.getUname() + "</option>");
            }
            model.addAttribute("school", str);

          /*  StringBuilder str2 = new StringBuilder();
            List<Object[]> jobs = doZZService.getDemands(pid);
            for (Object[] job : jobs) {
                str2.append("<option value='" + job[0] + "'>" + job[1] + "</option>");
            }
            model.addAttribute("jobs", str2);*/
            //招聘岗位
            List<ProjectInfoJobs> projectJobs=utilService.getProjectJobs(pid);
            model.addAttribute("jobs",projectJobs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "Do/ZZCampus/Post/index";
    }

    @SuppressWarnings("unchecked")
    @RequestMapping("/getusers")
    public void getusers(HttpServletRequest request, HttpServletResponse response, HRZZUser user) {
        try {
            int perpage = Integer.parseInt(request.getParameter("perpage"));
            int page = Integer.parseInt(request.getParameter("page"));
            String flowid = request.getParameter("flowid").trim();
            user.setPath("/" + flowid + "/");

            Map<String, Object> map = doZZService.getPostUsers(page, perpage, user);
            StringBuilder result = new StringBuilder();
            double pageCount = (Double) map.get("pageCount");
            double allcount = (Double) map.get("count");
            if (pageCount != 0) {
                Object object = map.get("list");
                int num = 0;
                for (Object[] _user : (List<Object[]>) object) {
                    //r.id,s.id as userid,r.name,r.gender,r.code,r.major,r.graduationtime,
                    //r.bx,r.guake,r.tc,u.point,r.deptname,r.gwname,r.op6,r.fqstate,r.fqfid
                    result.append("<tr><td><input type=\"checkbox\" name='uid' value='" + _user[0] + "' id='cb_" + _user[0] + "' /></td>");
                    result.append("<td>" + (perpage * (page - 1) + num + 1) + "</td>");
                    result.append("<td class='link'><a target='_blank' href='"
                            + request.getContextPath() + "/UserResume/ViewDResume?id="
                            + _user[0] + "'>" + _user[2]
                            + "</a></td>");//简历ID和HRZZUser的ID相同
                    result.append("<td>" + _user[3] + "</td>");
                    result.append("<td>" + _user[4] + "</td>");
                    result.append("<td>" + _user[5] + "</td>");
                    result.append("<td>" + _user[6] + "</td>");
                    result.append("<td>" + _user[7] + "</td>");
                    result.append("<td>" + _user[8] + "</td>");
                    result.append("<td>" + _user[9] + "</td>");
                    result.append("<td>" + _user[10] + "</td>");
                    result.append("<td>" + _user[11] + "</td>");
                    result.append("<td>" + (_user[12] == null ? "" : _user[12]) + "</td>");
                    if (_user[13].equals("未公布")) {
                        result.append("<td class='true'><span>" + _user[13] + "</span></td>");
                    } else {
                        result.append("<td class='false'><span>" + _user[13] + "</span></td>");
                    }
                    if (_user[14].equals("已放弃")
                            && _user[15].equals(flowid)) {
                        result.append("<td class='yfq'><span>已放弃</span></td></tr>");
                    } else {
                        boolean bl = (_user[15] != null && _user[15].equals(flowid));
                        result.append("<td class='" + bl + "'><span>" + (bl == true ? "未完成" : "已完成") + "</span></td></tr>");
                    }

                    num++;
                }
            } else {
                result.append("<tr style='display:none'><td></td></tr>");
            }
            result.append("<input type='hidden' id='pageCount' value='" + pageCount + "' />");
            result.append("<input type='hidden' id='allCount' value='" + allcount + "' />");
            utilService.printTextResult(result.toString(), response);
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printTextResult("<tr><td colspan='15'>读取数据失败</td></tr><input type='hidden' id='pageCount' value='0' /><input type='hidden' id='allCount' value='0' />", response);
        }

    }
    //[end]

    //[start] 岗位分配

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/PostAction", method = RequestMethod.POST)
    public void RAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String fid = request.getParameter("fid").trim();//招聘流程ID
            String hrcode = utilService.getConfig("hrcode");//招聘主管部门编码

            BaseUser cuser = utilService.getSessionUser(request);
            if (cuser.getUdept().equals(hrcode)) {
                //流程是否结束
                if (utilService.FlowIsDoing(fid)) {
                    List editlist = new ArrayList();
                    Date time = new Date();
                    //String gw = request.getParameter("gw").trim();//ProjectInfoJob的ID
                    String gwcode = request.getParameter("jobcode").trim();//BaseJob的code
                    String gwname = request.getParameter("jobname").trim();//BaseJob的name
                    //PlanPersondemand demand = doZZService.getDemand(gw);
                    String[] uids = request.getParameterValues("uid");
                    if (uids == null) {
                        utilService.printJsonResult(false, "请选择人员！", "no", response);
                    } else {
                        for (String uid : uids) {
                            HRZZUser usr = recommendService.getViewUser(uid);
                            if (usr.getFqstate().equals("未放弃")) {
                                usr.setGwdate(time);
                                //usr.setGwname(demand.getJobname());
                                usr.setGwname(gwname);
                                usr.setGwstate("已分配");
                                usr.setGwuid(cuser.getId());
                                usr.setGwuname(cuser.getUname());
                                editlist.add(usr);

                                DUserResume resume = doZZService.getResume(usr.getCode(), usr.getPid());
                                //resume.setJid(demand.getId());
                                //resume.setJname(demand.getJobname());
                                resume.setJid(gwcode);
                                resume.setJname(gwname);
                                editlist.add(resume);
                            }
                        }
                    }

                    if (editlist.size() > 0) {
                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "当前流程不支持此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]

    //[start] 流程扭转到下一步

    @SuppressWarnings({"rawtypes", "unchecked"})
    @RequestMapping(value = "/NextAction", method = RequestMethod.POST)
    public void NextAction(HttpServletRequest request, HttpServletResponse response) {
        try {
            String[] ids = request.getParameterValues("id");//人员信息ID
            if (ids != null) {
                String pid = request.getParameter("pid").trim();//招聘方案ID
                String fid = request.getParameter("fid").trim();//招聘流程ID
                String deptcode = request.getParameter("deptcode").trim();//责任部门编码
                String hrcode = utilService.getConfig("hrcode");//招聘主管部门编码
                BaseUser usr = utilService.getSessionUser(request);
                if (usr.getUdept().equals(hrcode)) {
                    List editlist = new ArrayList();
                    List<HRZZUser> users = doZZService.getUsers(pid, deptcode, ids);
                    ProjectInfoFlow nFlow = doZZService.getNextFlow(pid, deptcode, fid);
                    for (HRZZUser user : users) {
                        if (user.getFid().equals(fid)
                                && user.getGwstate().equals("已分配")
                                && user.getFqstate().equals("未放弃")) {
                            user.setFid(nFlow.getId());
                            user.setPath(user.getPath() + nFlow.getId() + "/");
                            editlist.add(user);
                        }
                    }

                    if (editlist.size() > 0) {
                        nFlow.setState(EnumTools.PlanFlowState.进行中.ordinal());
                        editlist.add(nFlow);

                        utilService.editList(editlist);
                        utilService.printJsonResult(true, "操作成功！", "no", response);
                    } else {
                        utilService.printJsonResult(false, "当前选中的信息不能执行此操作！", "no", response);
                    }
                } else {
                    utilService.printJsonResult(false, "您无权执行此操作！", "no", response);
                }
            } else {
                utilService.printJsonResult(false, "请选择人员信息！", "no", response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            utilService.printJsonResult(false, "操作失败！", "no", response);
        }
    }

    //[end]
}
